<template>
  <div v-loading="loading" element-loading-text="拼命加载中...">
    <!-- 顶部信息 -->
    <el-page-header v-if="showPageHeader" class="box-shadow mb-3" icon="arrow-left" @back="handleGoBack">
      <template #content>
        <span>线上店铺操作</span>
        <DictTag style="margin-left: 1rem" v-model="formData.status" :circle="false" dict-type="shop_status"/>
      </template>
      <template #extra>
        <div class="flex items-center">
          <template v-if="hasPermission('shop:info:audit')">
            <template v-if="!formData.heepay_merch_id && [30,32].includes(formData.status)">
              <el-button icon="circle-check-filled" type="success" @click="handleEntrySubmit">{{ !formData.heepay_apply_no ? '签约申请' : '签约修改' }}</el-button>
            </template>

            <!-- 已设置子商户号 -->
            <template v-if="formData.heepay_merch_id && [30,31,32,33].includes(formData.status)">
              <el-button icon="circle-check-filled" type="success" @click="handleEntryComplete">签约完成</el-button>
            </template>

            <!-- 审核操作 -->
            <template v-if="audit">
              <el-button icon="circle-check-filled" type="success" @click="handleAuditShow">审核操作</el-button>
            </template>
          </template>

          <template v-if="!readonly">
            <el-button icon="edit" type="primary" @click="onSubmitForm">保存修改</el-button>
          </template>
          <el-button v-if="readonly" icon="refresh" @click="handleRefresh">刷新信息</el-button>
          <el-button icon="arrow-left" @click="handleGoBack(false)">返回上页</el-button>
        </div>
      </template>
    </el-page-header>

    <div class="app-container-main">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基础信息" name="BaseInfo">

          <el-row :gutter="12">
            <el-col :md="12">
              <!-- 店铺信息 -->
              <el-card class="content-card">
                <div class="el-descriptions__header">
                  <div class="el-descriptions__title">店铺信息</div>
                </div>
                <el-form ref="formRef" :disabled="readonly" :model="formData" :rules="formRules" label-width="110px">
                  <el-form-item v-if="formData.id > 0 && readonly" label="店铺编号：">
                    <el-input v-model="formData.id" readonly/>
                  </el-form-item>

                  <el-form-item label="归属用户：" prop="user_id">
                    <SelectRemote v-model="account" api-url="/search/user/list" placeholder="请选择店铺归属用户" @change="handleUserSelectChange"/>
                  </el-form-item>

                  <el-form-item label="店铺分类：" prop="cate_id">
                    <TreeSelect ref="cateTreeRef" v-model="cateName" :tree-data="cateData" tree-placeholder="请选择店铺分类" @selectChange="handleSelectCate"/>
                  </el-form-item>

                  <el-form-item label="店铺名称：" prop="name">
                    <el-input v-model="formData.name" :maxlength="128" :readonly="readonly" autosize placeholder="请填写店铺名称" type="textarea"/>
                  </el-form-item>

                  <el-form-item label="店铺介绍：" prop="intro">
                    <el-input v-model="formData.intro" :autosize="{ minRows: 2}" :maxlength="200" :readonly="readonly" placeholder="请输入店铺介绍" type="textarea"/>
                  </el-form-item>

                  <el-form-item label="店铺封面：" prop="cover_url">
                    <UploadImage v-model="formData.cover_url" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                  </el-form-item>

                  <el-form-item label="联系人：" prop="contacts">
                    <el-input v-model="formData.contacts" :readonly="readonly" placeholder="请填写联系人"/>
                  </el-form-item>

                  <el-form-item label="联系方式：" prop="phone">
                    <el-input v-model="formData.phone" :maxlength="32" :readonly="readonly" placeholder="请填写店铺联系手机号"/>
                  </el-form-item>

                  <el-form-item label="邮箱账号：" prop="email">
                    <el-input v-model="formData.email" :maxlength="128" :readonly="readonly" autosize placeholder="请填写邮箱账号" type="textarea"/>
                  </el-form-item>

                  <el-form-item label="汇付编号：">
                    <el-input v-model="formData.heepay_merch_id" :maxlength="64" :readonly="readonly" placeholder="汇付宝商户编号" style="width: 60%;"/>
                    <el-button-group v-if="!readonly && formData.id > 0 && hasPermission([ 'shop:info:update'])" size="small" style="margin-left: 6px;margin-top: 6px">
                      <el-button type="primary" @click="handleUpdateHeepayMerchId">设置</el-button>
                    </el-button-group>
                  </el-form-item>

                  <el-form-item label="汇付类目：">
                    <el-select v-model="formData.heepay_cate_code" :disabled="readonly" clearable filterable placeholder="请选择汇付宝经营类目" style="width: 60%">
                      <el-option v-for="item in heepayCateOptions" :key="item.code" :label="'[' + item.code + '] ' + item.name" :value="item.code"/>
                    </el-select>
                  </el-form-item>

                  <el-divider border-style="dashed"/>
                  <el-form-item label="区域推荐：">
                    <el-select v-model="formData.region_recommend_id" :disabled="readonly" clearable filterable placeholder="请选择区域推荐" style="width: 60%">
                      <el-option v-for="item in recommendList" :key="item.id" :label="'[' + item.id + '] ' + item.name" :value="item.id"/>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-card>

            </el-col>

            <el-col :md="12">
              <!-- 店铺位置 -->
              <ShopLocation ref="mapLocationRef" v-model="shopLocationData" :readonly="readonly"/>
            </el-col>
          </el-row>

        </el-tab-pane>

        <el-tab-pane label="公司信息" name="BusinessLicense">

          <el-row :gutter="12">
            <el-col :md="12">
              <el-card class="content-card">
                <div class="el-descriptions__header">
                  <div class="el-descriptions__title">企业类型</div>
                </div>

                <!-- 企业类型 1:企业商户 2:个体工商户 3:小微商户 -->
                <el-radio-group v-model="formData.company_type" :disabled="readonly">
                  <el-radio-button :value="3" v-if="shopType == 20">小微商户</el-radio-button>
                  <el-radio-button :value="2" v-if="shopType == 20">个体工商户</el-radio-button>
                  <el-radio-button :value="1">企业商户</el-radio-button>
                </el-radio-group>
              </el-card>

              <!-- 店铺图片 -->
              <el-card class="content-card">
                <div class="el-descriptions__header">
                  <div class="el-descriptions__title">图片资料</div>
                </div>
                <el-form ref="imageFormRef" :disabled="readonly" :model="shopImageData" label-width="120px">
                  <!-- 企业类型 1:企业商户 2:个体工商户 3:小微商户 -->
                  <template v-if="formData.company_type == 1">
                    <el-form-item :rules="[{required: true, message: '请上传公司大楼照', trigger: 'blur'}]" label="公司大楼照：" prop="head_image_url">
                      <UploadImage v-model="shopImageData.head_image_url" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                    </el-form-item>
                    <el-form-item :rules="[{required: true, message: '请上传公司内景照', trigger: 'blur'}]" label="公司内景照：" prop="inside_image_url">
                      <UploadImage v-model="shopImageData.inside_image_url" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                    </el-form-item>
                    <el-form-item :rules="[{required: true, message: '请上传公司前台照', trigger: 'blur'}]" label="公司前台照：" prop="company_front_image_url">
                      <UploadImage v-model="shopImageData.company_front_image_url" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                    </el-form-item>
                  </template>

                  <template v-if="formData.company_type == 2 || formData.company_type == 3">
                    <el-form-item :rules="[{required: true, message: '请上传店铺门头照', trigger: 'blur'}]" label="店铺门头照：" prop="head_image_url">
                      <UploadImage v-model="shopImageData.head_image_url" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                    </el-form-item>
                    <el-form-item :rules="[{required: true, message: '请上传店铺内景照', trigger: 'blur'}]" label="店铺内景照：" prop="inside_image_url">
                      <UploadImage v-model="shopImageData.inside_image_url" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                    </el-form-item>
                    <el-form-item :rules="[{required: true, message: '请上传店铺收银台照', trigger: 'blur'}]" label="店铺收银台照：" prop="check_out_image_url">
                      <UploadImage v-model="shopImageData.check_out_image_url" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                    </el-form-item>
                  </template>
                </el-form>
              </el-card>

              <!-- 法人信息 -->
              <Certificate ref="legalPersonRef" v-model="certificateData" :readonly="readonly"/>
            </el-col>

            <el-col :md="12">
              <!-- 营业执照数据 -->
              <BusinessLicense v-if="formData.company_type == 1 || formData.company_type == 2" ref="businessLicenseRef" v-model="licenseData" :readonly="readonly"/>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="结算账户" name="SettlementAccount">
          <el-row :gutter="12">
            <el-col :md="12">
              <!-- 结算账户 -->
              <SettlementInfo ref="settlementInfoRef"
                              v-model="settlementAccountData"
                              :company-type="formData.company_type"
                              :readonly="readonly"
                              :shop-type="shopType"
                              @account-type="handleChangeSettlementAccountType"/>
            </el-col>

            <el-col v-if="settlementAccountType == 2" :md="12">
              <!-- 对私非法人账户 -->
              <Certificate ref="settlerRef" v-model="settlerData" :readonly="readonly" :settler="true"/>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 审核弹窗 -->
    <AuditDialog ref="auditRef" @submit-audit="handleAudit"/>
  </div>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from 'vue-router';
import { useTabsNavStore } from '@/store';
import { h, nextTick, onMounted, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElMessageBox, ElNotification, FormInstance, FormRules } from 'element-plus';
import { shopAudit, shopCategoryTreeList, shopEntryComplete, shopEntrySubmit, shopInfo, ShopRegionRecommend, shopRegionRecommendAll, shopSaveOrUpdate, shopUpdateHeepayMerchId } from '@/api/api-shop.ts';
import { AuditDialog, SelectRemote } from '@/components/other';
import { UploadImage } from '@/components/upload';
import BusinessLicense from '@/views/components/business-license.vue';
import Certificate from '@/views/components/certificate.vue';
import SettlementInfo from '@/views/components/settlement-info.vue';
import ShopLocation from '@/views/components/shop-location.vue';
import { TreeSelect } from '@/components/tree-select';
import { BaseCategory, BaseShopData, BusinessLicenseData, CertificateData, SettlementAccount, ShopImageData, ShopLocationData } from '@/api/common.ts';
import { hasPermission } from '@/utils/permission.ts';
import { emailRegex, phoneRegex } from '@/utils/validate.ts';
import { heepayCateOptions } from '@/utils/heepay-data.ts';
import { DictTag } from '@/components/dict-tag';

defineOptions({name: 'shop-info'});

const props = defineProps({
  id: {
    type: Number,
    required: true
  },
  readonly: {
    type: Boolean,
    default: false
  },
  audit: {
    type: Boolean,
    default: false
  },
  showPageHeader: {
    type: Boolean,
    default: true
  }
});

const shopType = ref(10);
const currentRoute = useRoute();
const tabsNavStore = useTabsNavStore();
const loading = ref(false);
const activeName = ref('BaseInfo');
const account = ref();
/** 默认表单数据 */
const defaultForm: BaseShopData = <BaseShopData>{id: 0, status: 0};
const formRef = ref<FormInstance>();
const formData = ref({...defaultForm});
// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  cate_id: [{required: true, message: '类目不能为空', trigger: 'blur'}],
  cover_url: [{required: true, message: '请上传店铺封面图', trigger: 'blur'}],
  user_id: [{required: true, message: '请选择归属用户', trigger: 'blur'}],
  phone: [{required: true, message: '联系方式不能为空', trigger: 'blur'}, {pattern: phoneRegex, message: '联系方式格式不正确', trigger: 'blur'}],
  email: [{pattern: emailRegex, message: '邮箱账号格式不正确', trigger: 'blur'}],
});

/** 营业执照数据 */
const defBusinessLicense: BusinessLicenseData = <BusinessLicenseData>{};
const licenseData = ref({...defBusinessLicense});

/** 法人信息 */
const defCertificateData: CertificateData = <CertificateData>{};
const certificateData = ref({...defCertificateData});

/** 结算账户信息 */
const defSettlementAccount: SettlementAccount = <SettlementAccount>{};
const settlementAccountData = ref({...defSettlementAccount});

/** 对私非法人结算者信息 */
const defSettlerData: CertificateData = <CertificateData>{};
const settlerData = ref({...defSettlerData});

/** 商户图片数据 */
const defShopImageData: ShopImageData = <ShopImageData>{};
const shopImageData = ref({...defShopImageData});

/** 店铺位置数据 */
const defShopLocationData: ShopLocationData = <ShopLocationData>{};
const shopLocationData = ref({...defShopLocationData});

/** 返回上一页 */
const router = useRouter();
const handleGoBack = async (refresh = false) => {
  await tabsNavStore.delView(currentRoute);
  let params = {refresh: refresh ? 1 : 0}
  await router.push({name: 'shop-list', state: {params}});
};

/** 刷新数据 */
const handleRefresh = async () => {
  await handleResetData();
  await initCateTreeData();
  await initRecommendList();
  await initData(props.id);
};

/** 重置数据 */
const handleResetData = async () => {
  activeName.value = 'BaseInfo';
  account.value = undefined;
  // 重置表单数据
  formData.value = {...defaultForm};
  formData.value.company_type = 1; // 企业类型 1:企业商户 2:个体工商户 3:小微商户
  // 重置界面表单数据
  formRef.value?.resetFields();
  // 重置营业执照数据
  licenseData.value = {...defBusinessLicense};
  // 法人证件信息
  certificateData.value = {...defCertificateData};
  // 结算账户信息
  settlementAccountData.value = {...defSettlementAccount}
  settlementAccountData.value.type = 3; // 账户类型 1:对私法人 2:对私非法人 3:对公账户
  // 对私非法人结算者信息
  settlerData.value = {...defSettlerData};
  // 商户图片数据
  shopImageData.value = {...defShopImageData};
  cateName.value = '';
  // 店铺位置数据
  shopLocationData.value = {...defShopLocationData};
};

/** 加载信息 */
const initData = async (id: number) => {
  if (!id || id <= 0) return;
  loading.value = true;
  try {
    const {data} = await shopInfo(id)
    formData.value = data;

    // 店铺归属用户
    account.value = formData.value.user_account;

    // 其他数据转换
    if (formData.value.image_data) {
      shopImageData.value = formData.value.image_data;
    }
    if (formData.value.business_license) {
      licenseData.value = formData.value.business_license;
    }
    if (formData.value.legal_person) {
      certificateData.value = formData.value.legal_person;
    }
    if (formData.value.account_data) {
      settlementAccountData.value = formData.value.account_data;
    }
    if (formData.value.settler_data) {
      settlerData.value = formData.value.settler_data;
    }

    // 区域推荐
    formData.value.region_recommend_id = formData.value.region_recommend_id || undefined;

    // 处理分类类目选择回显
    handleCateSetCurrentNode();

    // 设置地图位置数据
    shopLocationData.value = <ShopLocationData>{
      region_code: data.region_code,
      region_name: data.region_name,
      address: data.address,
      longitude: data.longitude,
      latitude: data.latitude
    };
    await nextTick(() => mapLocationRef.value?.addMapMarker());
  } finally {
    loading.value = false
  }
};

/** 数据提交 */
const mapFormRef = ref<FormInstance>();
const imageFormRef = ref<FormInstance>();
const businessLicenseRef = ref();
const legalPersonRef = ref();
const settlementInfoRef = ref();
const settlerRef = ref();
const mapLocationRef = ref();
const onSubmitForm = async () => {
  const v1 = formRef.value?.validate();
  const v2 = mapFormRef.value?.validate();
  const v3 = businessLicenseRef.value?.formValidate();
  const v4 = legalPersonRef.value?.formValidate();
  const v5 = settlementInfoRef.value?.formValidate();
  const v6 = settlerRef.value?.formValidate();
  const v7 = imageFormRef.value?.validate();
  const v_map = mapLocationRef.value?.formValidate();
  // 多表达验证
  Promise.all([v1, v2, v3, v4, v5, v6, v7, v_map]).then((res) => {
    // 封装请求参数
    let params = Object.assign({}, formData.value);
    params.image_data = shopImageData.value; // 商户图片数据
    params.business_license = licenseData.value; // 营业执照数据
    params.legal_person = certificateData.value; // 法人数据
    params.account_data = settlementAccountData.value; // 结算账户数据
    params.settler_data = undefined;
    // 如果店铺类型为 线下 且结算账户为 对私非法人
    if (settlementAccountData.value.type == 2) {
      params.settler_data = settlerData.value;
    }

    // 地区数据
    params.region_code = shopLocationData.value.region_code;
    params.region_name = shopLocationData.value.region_name;
    params.address = shopLocationData.value.address;
    params.longitude = shopLocationData.value.longitude;
    params.latitude = shopLocationData.value.latitude;

    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    shopSaveOrUpdate(params, params.id <= 0).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000})
      if (params.id <= 0) {
        // 返回上页
        handleGoBack(true);
      }
    }).finally(() => loading.close())
  }).catch((e) => {
    console.log(e)
    // 校检不通过
    ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
  })
};

/** 用户选择改变 */
const handleUserSelectChange = (val: any) => {
  formData.value.user_id = val ? val.id : undefined;
};

/** 结算账户类型改变 */
const settlementAccountType = ref();
const handleChangeSettlementAccountType = (type?: number) => {
  settlementAccountType.value = type;
  settlerData.value = {...defSettlerData};
};

/** 加载分类数据 */
const cateName = ref('');
const cateData = ref<BaseCategory[]>([]);
const cateTreeRef = ref();
const cateTreeLoading = ref(false)

/** 加成分类数据 */
const initCateTreeData = async () => {
  cateTreeLoading.value = true
  try {
    const {data} = await shopCategoryTreeList(false);
    cateData.value = data
  } finally {
    cateTreeLoading.value = false
  }
};

/** 处理分类选中 */
const handleSelectCate = (item?: any) => {
  formData.value.cate_id = item
};

const handleCateSetCurrentNode = () => {
  nextTick(() => {
    cateTreeRef.value?.handleSetCurrentNode(formData.value.cate_id)
  });
};

onMounted(async () => {
  await handleRefresh();
  await initData(props.id);
});

/** 审核弹窗 */
const auditRef = ref<any>();
const handleAuditShow = () => {
  auditRef.value?.open(formData.value.id);
};
/** 审核提交 */
const handleAudit = (data: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在提交中...',
    background: 'rgba(0, 0, 0, 0.2)'
  })
  // 提交数据
  shopAudit(data).then(response => {
    // 提示信息
    ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
    // 返回上页
    handleGoBack(true);
  }).finally(() => loading.close())
};

/** 设置汇宝商户编号 */
const handleUpdateHeepayMerchId = () => {
  ElMessageBox.prompt(h('p', null, ['是否确认设置店铺 ', h('span', {style: 'font-weight: bold'}, formData.value.name), ' 的汇付宝商家编号吗？',]), {
    title: '提示',
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入汇付宝商户编号',
  }).then(({value}) => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    let params = {
      id: formData.value.id,
      heepay_merch_id: value
    }
    // 提交数据
    shopUpdateHeepayMerchId(params).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000})
      formData.value.heepay_merch_id = value;
    }).finally(() => loading.close())
  });
};

/** 签约申请 */
const handleEntrySubmit = () => {
  ElMessageBox.confirm(h('p', null, ['是否将商户 ', h('span', {style: 'font-weight: bold;'}, formData.value.name), ` 进行 `, h('span', {style: 'font-weight: bold;'}, '签约申请'), `  操作吗？`]), '提示', {
    type: 'warning',
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    shopEntrySubmit(formData.value.id).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000})
    }).finally(() => loading.close())
  }).catch(() => {

  });
};

/** 签约完成 */
const handleEntryComplete = () => {
  ElMessageBox.confirm(h('p', null, ['是否将商户 ', h('span', {style: 'font-weight: bold;'}, formData.value.name), ` 更改为 `, h('span', {style: 'font-weight: bold;'}, '签约完成'), `  操作吗？`]), '提示', {
    type: 'warning',
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    shopEntryComplete(formData.value.id).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000})
      // 返回上页
      handleGoBack(true);
    }).finally(() => loading.close())
  }).catch(() => {

  });
};

/** 初始化区域推荐 */
const recommendList = ref<ShopRegionRecommend[]>([]);
const initRecommendList = async () => {
  recommendList.value = [];
  const {data} = await shopRegionRecommendAll();
  recommendList.value = data;
};

</script>

<style lang="scss" scoped>
.app-container-main {
  .el-form-item {
    margin-bottom: 16px !important;
  }

  :deep(.el-form-item__content) {
    max-width: 36rem;
  }

  .el-input-number {
    max-width: 10rem;
  }

  .el-descriptions__title {
    border-left: 3px solid var(--el-color-primary);
    padding-left: 10px;
    font-weight: 500;
    font-size: 14px;
    line-height: 16px;
  }
}
</style>
